# -*- coding: utf-8 -*-
# @Time    : 2019/5/18 11:20
# @Author  : awer
# @Email   : awer@awer.cn
# @File    : db_helper.py
# @Software: PyCharm
import datetime
from pony.orm import *

import helper
import options
import sign_helper

IS_BIND = False
db = Database()


class User(db.Entity):
    user_id = Required(int, size=64)
    group_id = Required(int, size=64)
    points = Required(int)
    charm = Required(int)
    power = Required(int)
    energy = Required(int)
    sign_date = Required(datetime.date)
    sign_num = Required(int)
    sign_continue = Required(int)
    desc = Optional(str)


@db_session
def get_user(user_id, group_id):
    u = User.get(user_id=user_id, group_id=group_id)
    print(str(u))


@db_session
def add_user(user_id, group_id, points):
    User(user_id=user_id, group_id=group_id,
         points=points,
         charm=0,
         power=0,
         energy=0,
         sign_date=datetime.datetime.today(),
         sign_num=1,
         sign_continue=1,
         desc=''
         )


@db_session
def update_user(user_id, group_id):
    u = User.get(user_id=user_id, group_id=group_id)
    if u:
        u.sign_date = datetime.date.today() - datetime.timedelta(days=1)


@db_session
def user_sign(user_id, group_id, points):
    u = User.get(user_id=user_id, group_id=group_id)
    suc = False
    if u is not None:
        if u.sign_date == datetime.date.today():
            re_msg = "[消息头]今天已经签到过了"

        elif u.sign_date < datetime.date.today():
            if u.sign_date == datetime.date.today() - datetime.timedelta(days=1):
                u.sign_continue += 1
            else:
                u.sign_continue = 1

            u_energy = sign_helper.get_power(u.sign_continue)
            u.points += points
            u.energy += u_energy
            u.sign_num += 1
            u.sign_date = datetime.date.today()

            suc = True
            re_msg = '[消息头]签到成功，积分+%d\r\n' \
                     '[消息头]您已连续签到%d天,能量+%d\r\n' \
                     '[消息头]累计签到天数 %d天\r\n' \
                     ' ' % (points, u.sign_continue, u_energy, u.sign_num)


    else:
        User(user_id=user_id, group_id=group_id,
             points=points,
             charm=0,
             power=0,
             energy=0,
             sign_date=datetime.datetime.now(),
             sign_num=1,
             sign_continue=1,
             desc=''
             )
        re_msg = '[消息头]签到成功，这是第一次签到，积分+%d\r\n' \
                 ' ' \
                 ' ' % (points)
        suc = True

    return {'suc': suc, 'msg': re_msg}


def init(root_path=''):
    global IS_BIND
    if not IS_BIND:
        db_path = helper.get_data_path()
        if len(root_path) > 0:
            db_path = root_path + '\\' + db_path

        sql_debug(True)
        db.bind("sqlite", filename=db_path, create_db=True, check_same_thread=False)
        db.generate_mapping(create_tables=True)
        IS_BIND = True
